package com.huaxindata.im.main.menu;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huaxin.common.AppManager;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.tools.Log;
import com.huaxin.common.utils.HxUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxindata.im.R;
import com.huaxindata.im.R2;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.main.contactview.friend.HxPersonalCenterActivity;
import com.huaxindata.im.main.contactview.friend.HxSearchContactAdapter;
import com.huaxindata.im.main.contactview.friend.model.UserModel;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.HxSearchByLonLatBean;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.view.StaticSearchBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 此页面用于搜索联系人的页面
 * 主要用于添加好友之前的搜索
 */
public class SearchContactActivity extends BaseActivity {
    private static final String TAG = "SearchContactActivity";

    private static final int SELECT_PHONE    = 0;//点击通讯录
    private static final int SELECT_AROUND   = 1;//点击附近
    private static final int SELECT_COMPANY  = 2;//点击企业
    private static final int SELECT_CUSTOMER = 3;//点击客服
    @BindView(R2.id.editView)
    EditText        mEditView;
    @BindView(R2.id.delete)
    ImageView       mDelete;
    @BindView(R2.id.search)
    TextView        mSearch;
    @BindView(R2.id.toolbar)
    StaticSearchBar mToolbar;
    @BindView(R2.id.add_friend_search_result_layout)
    LinearLayout    mAddFriendSearchResultLayout;
    @BindView(R2.id.add_friend_by_phone_tv)
    TextView        mAddFriendByPhoneTv;
    @BindView(R2.id.add_friend_by_around_tv)
    TextView        mAddFriendByAroundTv;
    @BindView(R2.id.add_friend_by_company_tv)
    TextView        mAddFriendByCompanyTv;
    @BindView(R2.id.add_friend_by_customer_tv)
    TextView        mAddFriendByCustomerTv;
    @BindView(R2.id.add_search_select_contact_layout)
    LinearLayout    mAddSearchSelectContactLayout;
    @BindView(R2.id.line_view)
    View            mLineView;
    @BindView(R2.id.add_friend_search_recycler)
    RecyclerView    mAddFriendSearchRecycler;
    @BindView(R2.id.search_fl)
    FrameLayout     mSearchFl;
    private List<Contact> mContacts = new ArrayList<>();
    private HxSearchContactAdapter  mContactAdapter;
    private View                    mNoDataView;
    private HxSearchContactFragment mSearchContactFragment;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_search_contact;
    }

    @Override
    public void initView() {
        mAddFriendByPhoneTv.setSelected(true);
        mAddFriendSearchRecycler.setLayoutManager(new LinearLayoutManager(this));
        mAddFriendSearchRecycler.setHasFixedSize(true);
        mContactAdapter = new HxSearchContactAdapter();
        mAddFriendSearchRecycler.setAdapter(mContactAdapter);

        //空界面
        mNoDataView = getLayoutInflater().inflate(R.layout.static_no_data, (ViewGroup) mAddFriendSearchRecycler.getParent(), false);
        mNoDataView.findViewById(R.id.no_data_ll).setVisibility(View.VISIBLE);


        initEditView();
        initSearch();
    }

    private void initEditView() {
        mEditView.setHint("输入手机号快速查询");
        mEditView.setSingleLine(true);
        mEditView.setInputType(InputType.TYPE_CLASS_PHONE);
    }

    /**
     * 搜索
     */
    private void initSearch() {
        mToolbar.setListener(new StaticSearchBar.SearchListener() {
            @Override
            public void doSearch(String keyword) {
                searchContact(keyword);
            }

            @Override
            public void cancel() {
                mSearchFl.setVisibility(View.GONE);
                AppManager.getAppManager().finishActivity(SearchContactActivity.this);
            }
        });
    }

    private void searchContact(String keyword) {
        if (!HxUtils.isPhone(keyword)) {
            ToastUtil.showToast("手机号错误");
            return;
        }
        mSearchFl.setVisibility(View.VISIBLE);
        mSearchContactFragment = HxSearchContactFragment.newInstance();

        SearchContactActivity.this.getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.search_fl, mSearchContactFragment)
                .commit();

        Call<UserModel> call = RetrofitClient.getHttpApi().findFriendByPhone(keyword);
        call.enqueue(new Callback<UserModel>() {
            @Override
            public void onResponse(Call<UserModel> call, Response<UserModel> response) {
                UserModel user = response.body();
                if (response.isSuccessful() && user != null) {
                    ContactPerson contact = new ContactPerson();
                    contact.setNickName(user.getNickName());
                    contact.setPhone(user.getTelPhone());
                    contact.setIcon(user.getImgUrl());
                    contact.setClientId(user.getUserId() + "");
                    mSearchContactFragment.setSearchData(contact);
                } else {
                    ToastUtil.showToast("数据异常");
                }
               /* if (user.getState() == 1) {
                    ContactPerson person = user.toPerson();
                    //showContactInfo(SearchContactActivity.this, person);
                } else {

                }*/
            }

            @Override
            public void onFailure(Call<UserModel> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });
    }

    @Override
    public void initData() {
        onFriendPhoneData();
    }

    @OnClick(R2.id.add_friend_by_phone_tv)
    public void onViewClicked(View view) { //企业认证
        clickedSelectTextColor(SELECT_PHONE);
        onFriendPhoneData();
    }

    @OnClick(R2.id.add_friend_by_around_tv)
    public void onViewClicked1(View view) { //附近
        clickedSelectTextColor(SELECT_AROUND);
        onNearbyData(BaseApp.getLatLng());
    }

    @OnClick(R2.id.add_friend_by_company_tv)
    public void onViewClicked2(View view) { //企业

        clickedSelectTextColor(SELECT_COMPANY);
        onCompanyData();
    }

    @OnClick(R2.id.add_friend_by_customer_tv)
    public void onViewClicked3(View view) { //客服
        clickedSelectTextColor(SELECT_CUSTOMER);
        onCustomerData();
    }

    /**
     * 选择TextView字体颜色
     */
    private void clickedSelectTextColor(int select_postion) {
        switch (select_postion) { //R.id.accent
            case SELECT_PHONE:
                mAddFriendByPhoneTv.setSelected(true);
                mAddFriendByAroundTv.setSelected(false);
                mAddFriendByCompanyTv.setSelected(false);
                mAddFriendByCustomerTv.setSelected(false);
                break;
            case SELECT_AROUND:
                mAddFriendByPhoneTv.setSelected(false);
                mAddFriendByAroundTv.setSelected(true);
                mAddFriendByCompanyTv.setSelected(false);
                mAddFriendByCustomerTv.setSelected(false);
                break;
            case SELECT_COMPANY:
                mAddFriendByPhoneTv.setSelected(false);
                mAddFriendByAroundTv.setSelected(false);
                mAddFriendByCompanyTv.setSelected(true);
                mAddFriendByCustomerTv.setSelected(false);
                break;
            case SELECT_CUSTOMER:
                mAddFriendByPhoneTv.setSelected(false);
                mAddFriendByAroundTv.setSelected(false);
                mAddFriendByCompanyTv.setSelected(false);
                mAddFriendByCustomerTv.setSelected(true);
                break;
        }
        mSearchFl.setVisibility(View.GONE);
    }

    /**
     * 手机通讯录数据
     */
    private void onFriendPhoneData() {
        mContacts.clear();
        mContacts.addAll(ContactManager.loadLocalContactList(this));
        mContactAdapter.setNewData(mContacts);
        mContactAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Contact contact = mContacts.get(position);
                Log.d(TAG, "昵称--->" + contact.getNickName());

             /*   ContactInfoDialog contactInfoDialog = new ContactInfoDialog(SearchContactActivity.this);
                contactInfoDialog.setOwnerActivity(SearchContactActivity.this);
                contactInfoDialog.show(contact);*/

                Intent intent = new Intent(SearchContactActivity.this, HxPersonalCenterActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("contact", contact);
                intent.putExtras(bundle);
                SearchContactActivity.this.startActivity(intent);
            }
        });
    }

    /**
     * 附近人信息
     */
    private void onNearbyData(LatLng latLng) {
        mContacts.clear();
        Call<HxSearchByLonLatBean> call = RetrofitClient.getHttpApi().findFriendByNear
                (latLng.longitude, latLng.latitude);
        call.enqueue(new Callback<HxSearchByLonLatBean>() {
            @Override
            public void onResponse(Call<HxSearchByLonLatBean> call, Response<HxSearchByLonLatBean> response) {
                if (response.isSuccessful()) {
                    List<HxSearchByLonLatBean.UsersBean> usersBeans = response.body().getUsers();
                    for (HxSearchByLonLatBean.UsersBean usersBean : usersBeans) {
                        ContactPerson contact = new ContactPerson();
                        String imgUrl = usersBean.getImgUrl();
                        String nickName = usersBean.getNickName();
                        String telPhone = usersBean.getTelPhone();
                        String title = usersBean.getTitle();
                        int userId = usersBean.getUserId();
                        contact.setIcon(imgUrl);
                        contact.setNickName(nickName);
                        contact.setPhone(telPhone);
                        contact.setClientId("" + userId);
                        contact.setDuty(title);
                        LatLng laglng = new LatLng(usersBean.getLat(), usersBean.getLon());
                        contact.setLatLng(laglng);
                        mContacts.add(contact);
                    }
                    mContactAdapter.setNewData(mContacts);
                } else {
                    mContactAdapter.setEmptyView(mNoDataView);
                }
            }

            @Override
            public void onFailure(Call<HxSearchByLonLatBean> call, Throwable t) {
                mContactAdapter.setEmptyView(mNoDataView);
            }
        });
    }

    /**
     * 企业数据
     */
    private void onCompanyData() {
        //如果此用户的公司名是默认的，即是普通用户
        mContacts.clear();
        if (TextUtils.isEmpty(UserManager.getCompanyName())) {
            mContactAdapter.setNewData(mContacts);
            mContactAdapter.setEmptyView(mNoDataView);
        } else {
            mContacts.addAll(ContactManager.getColleagueList());
            mContactAdapter.setNewData(mContacts);

        }
    }

    /**
     * 客服数据
     */
    private void onCustomerData() {
        mContacts.clear();
        mContacts.addAll(getKeFuList());
        mContactAdapter.setNewData(mContacts);
    }

    /**
     * 生成固定的客服：
     * {
     * "company": "武汉华信数据系统有限公司",
     * "email": "admin@123.com.cn",
     * "imgUrl": "",
     * "lat": 1,
     * "lon": 1,
     * "nickName": "管理员",
     * "orgCode": "HUAXIN",
     * "orgName": "武汉华信数据系统有限公司",
     * "sex": 0,
     * "telPhone": "87775236",
     * "title": "系统管理员",
     * "userId": 50
     * }
     */
    private List<Contact> getKeFuList() {
        List<Contact> kefuList = new ArrayList<>();
        ContactPerson contactPerson1 = new ContactPerson("50", "管理员", "");
        contactPerson1.setTitle("系统管理员");
        contactPerson1.setPhone("87775236");
        contactPerson1.setCompany("武汉华信数据系统有限公司");
        // contactPerson1.latLng=new LatLng(1, 1);
        kefuList.add(contactPerson1);

        ContactPerson contactPerson2 = new ContactPerson("403", "客服", "");
        contactPerson2.setTitle("客服");
        contactPerson2.setPhone("123456");
        contactPerson2.setCompany("武汉华信数据系统有限公司");
        //        contactPerson2.latLng=new LatLng(1, 1);
        kefuList.add(contactPerson2);
        return kefuList;
    }

}
